<template>
  <div class="countContainer">
    <div class="item">
      <span class="name">{{$t('message.xmindMap.numberWords')}}</span>
      <span class="value">{{ words }}</span>
    </div>
    <div class="item">
      <span class="name">{{$t('message.xmindMap.node')}}</span>
      <span class="value">{{ num }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance,
  onBeforeUnmount
} from 'vue' 
import type {ComponentInternalInstance} from 'vue'
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
import { useRouter } from "vue-router"
const router = useRouter();

const emit = defineEmits([""])
const props = defineProps({
  mindMap: {
    type: Object
  }
})
import { conforms } from 'lodash';
let countEl = document.createElement('div')
const words = ref(0)
const num = ref(0)
const textStr = ref('')
onMounted(()=>{
  proxy.$eventBus.$on("data_change", onDataChange);
  if (props.mindMap) {
    onDataChange(props.mindMap.getData())
  }
})
onBeforeUnmount(()=>{
  proxy.$eventBus.$off('data_change', onDataChange)
})
/**
 * @Desc: 监听数据变化
 */
function onDataChange(data) {
  textStr.value = ''
  words.value = 0
  num.value = 0
  walk(data)
  countEl.innerHTML = textStr.value
  words.value = countEl.textContent.length
}
/**
 * @Desc: 遍历
 */
function walk(data) {
  num.value++
  textStr.value += String(data.data.text) || ''
  if (data.children && data.children.length > 0) {
    data.children.forEach(item => {
      walk(item)
    })
  }
}
</script>
<style lang="scss" scoped>
.countContainer {
  @include fontFamily;
  padding: 0 12px;
  position: fixed;
  left: 20px;
  bottom: 20px;
  background: hsla(0, 0%, 100%, 0.8);
  border-radius: 2px;
  opacity: 0.8;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
  display: flex;

  .item {
    color: #555;
    margin-right: 15px;

    &:last-of-type {
      margin-right: 0;
    }

    .name {
      margin-right: 5px;
    }
  }
}
</style>